package concurrent.forkjoin;

import java.util.concurrent.RecursiveTask;

/**
 *
 */
public class SumTask extends RecursiveTask<Long> {
    protected long[] arrays;
    protected int start, end;

    public static int threshold = 10000;

    public SumTask(long[] arrays) {
        this(arrays, 0, arrays.length);
    }

    public SumTask(long[] arrays, int start, int end) {
        this.arrays = arrays;
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        int length = end - start;
        if (length <= threshold) {
            return computePart();
        }

        int middle = (end + start) / 2;
        SumTask left = new SumTask(arrays, start, middle);
        SumTask right = new SumTask(arrays, middle, end);
        right.fork();
        long leftValue = left.compute();
        long rightValue = right.join();
        return leftValue + rightValue;
    }

    protected long computePart() {
        long sum = 0;
        for (int i = start; i < end; i++) {
            sum += arrays[i];
        }
        return sum;
    }
}
